/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package co.com.smart.hawk.view.impl;

import co.com.smart.connection.model.manager.EntityManagerProvider;
import co.com.smart.eagle.dto.EagleUsuarioDTO;
import co.com.smart.eagle.dto.LoginDTO;
import co.com.smart.eagle.servicehandler.login.SmartEagleServiceLogin;
import co.com.smart.eagle.servicehandler.login.SmartEagleServiceLoginImpl;
import co.com.smart.hawk.dto.UsuarioDTO;
import co.com.smart.hawk.utilities.HawkSessionMgr;
import co.com.smart.hawk.utilities.HawkViewMgr;
import co.com.smart.hawk.utilities.PanelCargando;
import co.com.smart.hawk.utilities.Utility.CallBackSmartHawk;
import co.com.smart.hawk.view.HawkLoginView;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;

/**
 *
 * @author Andres
 */
public class HawkLoginViewImpl extends javax.swing.JFrame implements HawkLoginView {

    PanelCargando panelcargando = new PanelCargando();

    /**
     * Creates new form HawkLoginViewImpl
     */
    public HawkLoginViewImpl() {

        if (HawkViewMgr.getInstance().getObjectInstance(this.getClass()) == null) {
            initComponents();
            this.setLocationRelativeTo(null);



            this.addWindowListener(new WindowAdapter() {

                @Override
                public void windowClosing(WindowEvent e) {
                    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {

                        @Override
                        protected Void doInBackground() throws Exception {
                            return null;
                        }

                        @Override
                        protected void done() {
                            cancelarProceso();
                        }
                    };
                    worker.execute();
                }
            });

            HawkViewMgr.getInstance().setObjectInstance(this);

        }
    }

    private void cancelarProceso() {
        int message = JOptionPane.showConfirmDialog(this, "Está seguro que desea salir?", "Salir", JOptionPane.YES_NO_OPTION);
        if (message == JOptionPane.YES_OPTION) {
            EntityManagerProvider.getProvider("SmartHawkPU").closeResources();
            HawkViewMgr.getInstance().removeObjectInstance(this.getClass());
            System.gc();
            this.dispose();
            System.exit(0);
        }
    }
    
    
    private void login(){
        if ("".equals(this.txtUsuario.getText())) {
            JOptionPane.showMessageDialog(this, "El usuario es obligatorio", "Validación", JOptionPane.WARNING_MESSAGE);
        } else if (jPasswordField1.getPassword() == null) {
            JOptionPane.showMessageDialog(this, "El la contraseña es obligatoria", "Validación", JOptionPane.WARNING_MESSAGE);
        } else {
            SmartEagleServiceLogin loginSmartEagle = new SmartEagleServiceLoginImpl();
            EagleUsuarioDTO user = new EagleUsuarioDTO();    
            user.setNombreUsuario(txtUsuario.getText());
            user.setClave(String.valueOf(jPasswordField1.getPassword()));
            LoginDTO login = loginSmartEagle.loginSmart(user);
            initLogin(login);

        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpDatos = new javax.swing.JPanel();
        jpTitulo = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        btIngresar = new javax.swing.JButton();
        lblUsuario = new javax.swing.JLabel();
        txtUsuario = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jPasswordField1 = new javax.swing.JPasswordField();
        jLabel3 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle(":.SmartEagle.:");
        setIconImage(new ImageIcon(getClass().getResource("/img/smart-jungle.png")).getImage());
        setResizable(false);
        setType(java.awt.Window.Type.POPUP);

        jpDatos.setBackground(new java.awt.Color(255, 255, 255));
        jpDatos.setAlignmentX(0.0F);
        jpDatos.setAlignmentY(0.0F);
        jpDatos.setAutoscrolls(true);
        jpDatos.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jpDatos.setDebugGraphicsOptions(javax.swing.DebugGraphics.NONE_OPTION);
        jpDatos.setFont(new java.awt.Font("Arial Narrow", 0, 30)); // NOI18N
        jpDatos.setPreferredSize(new java.awt.Dimension(520, 320));

        jpTitulo.setBackground(new java.awt.Color(0, 0, 102));
        jpTitulo.setForeground(new java.awt.Color(0, 0, 102));
        jpTitulo.setAlignmentX(0.0F);
        jpTitulo.setAlignmentY(0.0F);

        jLabel1.setBackground(new java.awt.Color(122, 140, 188));
        jLabel1.setFont(new java.awt.Font("Arial Narrow", 0, 40)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(255, 255, 255));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Autenticación SmartEagle");

        javax.swing.GroupLayout jpTituloLayout = new javax.swing.GroupLayout(jpTitulo);
        jpTitulo.setLayout(jpTituloLayout);
        jpTituloLayout.setHorizontalGroup(
            jpTituloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpTituloLayout.createSequentialGroup()
                .addGap(37, 37, 37)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 425, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jpTituloLayout.setVerticalGroup(
            jpTituloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpTituloLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(12, Short.MAX_VALUE))
        );

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

        jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/logo_smart_jungle.png"))); // NOI18N

        btIngresar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/smart_llave.PNG"))); // NOI18N
        btIngresar.setBorder(null);
        btIngresar.setBorderPainted(false);
        btIngresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btIngresarActionPerformed(evt);
            }
        });

        lblUsuario.setBackground(new java.awt.Color(255, 255, 255));
        lblUsuario.setFont(new java.awt.Font("Arial Narrow", 1, 30)); // NOI18N
        lblUsuario.setForeground(new java.awt.Color(0, 0, 102));
        lblUsuario.setText("Usuario");

        txtUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtUsuarioActionPerformed(evt);
            }
        });

        jLabel2.setBackground(new java.awt.Color(255, 255, 255));
        jLabel2.setFont(new java.awt.Font("Arial Narrow", 1, 30)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(0, 0, 102));
        jLabel2.setText("Contraseña");

        jPasswordField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jPasswordField1KeyPressed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel3.setText("Recuerde que para acceder al sistema Hawk, debe ser un usuario autorizado Smart.");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)
                            .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btIngresar, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel3))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(36, 36, 36)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(lblUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel2)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 23, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btIngresar, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        javax.swing.GroupLayout jpDatosLayout = new javax.swing.GroupLayout(jpDatos);
        jpDatos.setLayout(jpDatosLayout);
        jpDatosLayout.setHorizontalGroup(
            jpDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpDatosLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(11, Short.MAX_VALUE))
            .addComponent(jpTitulo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jpDatosLayout.setVerticalGroup(
            jpDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpDatosLayout.createSequentialGroup()
                .addComponent(jpTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(26, Short.MAX_VALUE))
        );

        getContentPane().add(jpDatos, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtUsuarioActionPerformed
    }//GEN-LAST:event_txtUsuarioActionPerformed

    private void jPasswordField1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPasswordField1KeyPressed
        // TODO add your handling code here:
        
        if(evt.getKeyCode() == KeyEvent.VK_ENTER){
            login();
        }
        
    }//GEN-LAST:event_jPasswordField1KeyPressed

    private void btIngresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btIngresarActionPerformed
        // TODO add your handling code here:
        login();
    }//GEN-LAST:event_btIngresarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btIngresar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPasswordField jPasswordField1;
    private javax.swing.JPanel jpDatos;
    private javax.swing.JPanel jpTitulo;
    private javax.swing.JLabel lblUsuario;
    private javax.swing.JTextField txtUsuario;
    // End of variables declaration//GEN-END:variables

    private void initLogin(LoginDTO login) {
        if (login != null && !"".equals(login.getPassword()) && login.getPassword() != null) {

            
            UsuarioDTO user = new UsuarioDTO();
            user.setCocodigo(login.getUser());
            user.setDsusuario(login.getUser());
            user.setDsclave(login.getPassword());
            HawkSessionMgr.getInstance().setSession("USER_SESSION", user);
            HawkMenuImpl hawkMenu = new HawkMenuImpl();
            hawkMenu.setVisible(true);
            hawkMenu.pack();
            HawkViewMgr.getInstance().removeObjectInstance(this.getClass());
            System.gc();
            this.dispose();

        } else {
            JOptionPane.showMessageDialog(this, "El usuario ingresado no es valido", "Validación", JOptionPane.ERROR_MESSAGE);
        }
    }

    @Override
    public LoginDTO obtenerUsuario() {
        return null;

    }

    @Override
    public void mostrarView() {
    }
}
